package com.xueke.crawler.service.download;

import com.xueke.crawler.helper.ProxyHelper;
import com.xueke.crawler.model.DocRelation;
import com.xueke.crawler.model.User;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by weibo on 2017/5/13.
 *
 * @author weibo.qin
 * @version 2017/5/13
 */
@Component("superUserDownloader")
public class SuperUserDownloader extends BaseDownloader {

    static Map<String, String> superUserMap = new HashMap<String, String>();

    static {
        //superUserMap.put("tzbm", "dtgr59");
        superUserMap.put("qthgjzx01", "qthgjzx");
        //superUserMap.put("ahgdfz", "n42637");
    }

    @Override
    public void download(int start, int end, int level, String userType) {
        Iterator<String> iterator = superUserMap.keySet().iterator();
        Map<String,String> cookies = new HashMap<String,String>();
        while (iterator.hasNext()) {
            String userName = iterator.next();
            String password = superUserMap.get(userName);

            int pageSize = 800;

            List<DocRelation> list = docRelationMapper.query2DownloadDocRelation(start, end, level, 0, pageSize);

            if (list.isEmpty()) {
                System.out.println("题目已经下载完毕！");
                return;
            }

            System.out.println(userName + "--------" + password);
            for (DocRelation docRelation : list) {
                
                 try {
                    String downloadUrl = ProxyHelper.parseSuper(String.valueOf(docRelation.getDocId()), userName,
                        password,cookies);
                    System.out.println(downloadUrl);

                     if ("-9999".equalsIgnoreCase(downloadUrl)) {
                         // 更新账户作废.
                         userMapper.updateUserStatus(userName);
                         break;
                     }

                     if ("-9998".equalsIgnoreCase(downloadUrl)) {
                         // 题目作废.
                         docRelationMapper.updateInvalidDoc(String.valueOf(docRelation.getDocId()));
                         break;
                     }

                    doDownload(downloadUrl, docRelation.getDocId(),cookies);
                } catch (Exception e) {
                    e.printStackTrace();

                }

            }


        }

    }
}
